#include "db_conninfo.h"
#include "opengauss/libpq-fe.h"
#include <unordered_map>
#include <vector>
#include <regex>
#include <string>
#include <iostream>

int GetsDbTypes(PGconn *conn, std::string &dbtypes)
{
    int nFields;
    int i, j;

    // 执行查询语句
    PGresult *res = PQexec(conn, "select version()");
    if (PQresultStatus(res) != PGRES_TUPLES_OK)
    {
        fprintf(stderr, "查询失败: %s", PQerrorMessage(conn));
        PQclear(res);
        PQfinish(conn);
        return 1;
    }

    // 获取结果集中的行数
    int rows = PQntuples(res);
    nFields = PQnfields(res);
    /* 打印行 */
    for (j = 0; j < nFields; j++)
    {

        // 遍历结果集，获取所需两个字段的值
        for (int i = 0; i < rows; i++)
        {
            const char *value1 = PQgetvalue(res, i, j);
            dbtypes = value1;
        }
    }

    // 释放结果集和关闭数据库连接
    PQclear(res);
    // PQfinish(conn);
    return 0;
}

std::string detectDatabaseType(PGconn *conn)
{
    int dbstatus;
    std::string dbtypes;
    dbstatus = GetsDbTypes(conn, dbtypes);
    if (dbstatus != 0)
    {
        std::cerr << "连接数据库出错: " << PQerrorMessage(conn) << std::endl;
    }
    std::string lowerStr = dbtypes;
    std::transform(lowerStr.begin(), lowerStr.end(), lowerStr.begin(), ::tolower);
    if (lowerStr.find("opengauss") != std::string::npos)
    {
        return "openGauss";
    }
    else if (lowerStr.find("postgresql") != std::string::npos)
    {
        return "PostgreSQL";
    }
    return "Unknown"; // 添加默认返回值
}